import React, { useCallback } from 'react';
import { Button, Table, Card, Box, Form, Icon, Field, Input, Select, Pagination, Badge } from '@alifd/next';
import { useFusionTable, useSetState } from 'ahooks';
import { FormattedMessage, FormattedNumber, useIntl } from 'react-intl';

import styles from './index.module.scss';
import { CommodityStatusEnums, getNextActionListSpan, SelectRequestConfig } from '../../entity';
import CreateDialog from '../CreateDialog';
import CommodityService from '../../service';
import CategoryService from '@/pages/CommodityCenter/CategoryManage/service';
import BrandService from '@/pages/CommodityCenter/BrandManage/service';
import { getEnumLabel } from '@/utils/enum';
import { useRequest } from 'ice';
import TableEmptyBlock from '@/components/TableEmptyBlock';

const { Column } = Table;

const FormItem = Form.Item;

interface MultiColState {
  expandStatus: boolean;
  actionListSpan: number;
}

const FilterList: React.FunctionComponent = (): JSX.Element => {
  const intl = useIntl();
  const field = Field.useField([]);

  const { data: brandList, request: brandRequest } = useRequest(BrandService.getBrandPage, SelectRequestConfig);

  const { data: categoryList, request: categoryRequest } = useRequest(CategoryService.getCategoryPage, SelectRequestConfig);


  // 禁用、启用
  const { request } = useRequest(CommodityService.changeStatus, {
    manual: true,
    onSuccess: () => { refresh(); },
    onError: () => { refresh(); },
  });

  // 搜索状态
  const [formState, setFormState] = useSetState<MultiColState>({
    expandStatus: false,
    actionListSpan: getNextActionListSpan(false),
  });

  const [dialogState, setDialogState] = useSetState({ visible: false, row: {} as any });

  const { paginationProps, tableProps, search, error, refresh } = useFusionTable(CommodityService.getProductPage, {
    field,
  });
  const { submit, reset } = search;

  const switchStatus = useCallback((row: CommodityState.CommodityItem, status: number) => {
    request({ id: row.id, status });
  }, [request]);

  const handleSetExpand = useCallback(() => {
    const nextExpand = !formState.expandStatus;
    setFormState({
      expandStatus: nextExpand,
      actionListSpan: getNextActionListSpan(nextExpand),
    });
  }, [formState, setFormState]);

  return (
    <Card free>
      <Card.Content>
        <Box spacing={20}>
          <Form colon responsive fullWidth labelAlign="top" field={field}>
            <FormItem colSpan={3} label="品牌" name="BrandId">
              <Select
                showSearch
                hasClear
                filterLocal={false}
                onSearch={(val) => brandRequest({ current: 1, pageSize: 10 }, { name: val, enable: true })}
                dataSource={brandList}
                placeholder="输入品牌名称"
              />
            </FormItem>
            <FormItem colSpan={3} label="类目" name="categoryId">
              <Select
                showSearch
                hasClear
                filterLocal={false}
                onSearch={(val) => categoryRequest({ current: 1, pageSize: 10 }, { name: val, enable: true })}
                dataSource={categoryList}
                placeholder="输入类目名称"
              />
            </FormItem>
            <FormItem colSpan={3} label="状态" name="status">
              <Select dataSource={CommodityStatusEnums} hasClear />
            </FormItem>
            {!formState.expandStatus ? null : (
              <FormItem colSpan={3} label="商品名称" name="productName">
                <Input placeholder="请输入" hasClear />
              </FormItem>
            )}
            <FormItem colSpan={formState.actionListSpan} label={formState.expandStatus ? '' : ' '} colon={false}>
              <Box direction="row" justify="flex-end" align="center">
                <Form.Submit type="primary" onClick={submit} validate style={{ marginRight: 10 }}>
                  提交
                </Form.Submit>
                <Form.Reset onClick={reset} style={{ marginRight: 10 }}>
                  重置
                </Form.Reset>
                <Button onClick={handleSetExpand} text>
                  {formState.expandStatus ? (
                    <>
                      收起
                      <Icon type="arrow-up" />
                    </>
                  ) : (
                    <>
                      展开
                      <Icon type="arrow-down" />
                    </>
                  )}
                </Button>
              </Box>
            </FormItem>
          </Form>
          <div>
            <Button type="primary" iconSize="xs" onClick={() => setDialogState({ visible: true })}>
              <Icon type="add" />
              添加商品
            </Button>
          </div>
          <Table
            {...tableProps}
            emptyContent={<TableEmptyBlock error={error} onRefresh={refresh} />}
            hasBorder={false}
            primaryKey="id"
          >
            <Column dataIndex="id" title="商品编号" align="center" />
            <Column
              dataIndex="name"
              title="商品信息"
              cell={(val, i, row) => (
                <div className={styles.baseinfo}>
                  <img
                    className={styles.img}
                    src={row.mainImage}
                    alt="商品主图"
                  />
                  <div>
                    <span className={styles.title}>{val}</span>
                    <div className={styles.row}>
                      <span>{`${row.brandName}/${row.categoryName}`}</span>
                      <span>{`规格:${row.attrValues || '无'}`}</span>
                    </div>
                  </div>
                </div>
              )}
            />
            <Column
              dataIndex="marketPrice"
              title="市场价"
              cell={(val) => intl.formatNumber(val || 0, { style: 'currency', currency: 'USD' })}
            />
            <Column
              dataIndex="status"
              title="状态"
              align="center"
              cell={(val) => (
                <div>
                  <Badge
                    dot
                    style={{
                      marginRight: 5,
                      backgroundColor: getEnumLabel(CommodityStatusEnums, val, ['value', 'color']),
                    }}
                  />
                  {getEnumLabel(CommodityStatusEnums, val)}
                </div>
              )}
            />
            <Column
              dataIndex="createTime"
              title="创建时间"
              cell={(val) => intl.formatDate(val, { hourCycle: 'h24', dateStyle: 'short', timeStyle: 'short' })}
            />
            <Column
              dataIndex="opera"
              title="操作"
              cell={(val, i, row) => (
                <Box direction="row" spacing={10} justify="center">
                  {[1, 3].includes(row.status) ? (
                    <Button type="primary" text onClick={() => switchStatus(row, 2)}>
                      {row.status === 1 ? '发布' : '上架'}
                    </Button>
                  ) : null}
                  {row.status === 2 ? (
                    <Button type="primary" text onClick={() => switchStatus(row, 3)}>
                      下架
                    </Button>
                  ) : null}
                  <Button type="primary" text onClick={() => setDialogState({ visible: true, row })}>
                    编辑
                  </Button>
                </Box>
              )}
            />
          </Table>
          <Pagination
            style={{ textAlign: 'end' }}
            shape="arrow-only"
            totalRender={(total) => <FormattedMessage id="page.total" tagName="div" values={{ total }} />}
            {...paginationProps}
          />
        </Box>
      </Card.Content>
      <CreateDialog
        visible={dialogState.visible}
        row={dialogState.row}
        onRefresh={refresh}
        onClose={() => setDialogState({ visible: false, row: {} })}
      />
    </Card >
  );
};

export default FilterList;
